package com.woniuxy.interceptor;

import com.woniuxy.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从Cookie中获取token
        Cookie tokenCookie = WebUtils.getCookie(request,"token");
        String tokenC = tokenCookie != null ? tokenCookie.getValue() : "";
        //从请求中获取token
        String tokenR = request.getParameter("token");
        //如果请求中包含token则优先使用请求中的token
        String token = tokenR != null ? tokenR : tokenC;

        //判断是否携带了token
        if (!StringUtils.isEmpty(token)) {
            //如果携带token，验证token
            boolean b = JwtUtils.verifyToken(token);
            //如果token能被解析成功，则放行，保存cookie到客户端
            if (b) {
                String backUrl = request.getParameter("backUrl");
                response.sendRedirect(backUrl+"?token="+token);
                return true;
            }else{
                //token解析失败则跳转到认证中心登录
                return true;
            }
        }else {
            //没有携带token则直接放行去目标
            return true;
        }
    }
}
